package org.flycloud.web.sso.client;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.flycloud.web.sso.common.SystemSession;
import org.flycloud.web.sso.common.Token;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ClientController {

	@Value("${sso.client.url.logout}")
	private String ssoLogoutUrl;

	@RequestMapping("/sso/ci")
	public void login(HttpServletRequest request, HttpServletResponse response) {
		String token = (String) request.getSession().getAttribute(Token.TOKEN);
		String target = request.getParameter("url");
		UsernamePasswordToken t = new UsernamePasswordToken(token, SystemSession.PASSWORD);
		try {
			Subject s = SecurityUtils.getSubject();
			s.login(t);
			request.getSession().setAttribute("login", true);
			response.sendRedirect(URLDecoder.decode(target, "UTF8"));
		} catch (AuthenticationException | IOException e1) {
			e1.printStackTrace();
		}
	}

	@RequestMapping("/sso/co")
	public void logout(HttpServletRequest request, HttpServletResponse response) {
		Subject s = SecurityUtils.getSubject();
		s.logout();
		request.getSession().removeAttribute("login");
		request.getSession().removeAttribute(Token.TOKEN);
		try {
			response.sendRedirect(ssoLogoutUrl);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping("/sso/ri")
	@ResponseBody
	public String rlogin(HttpServletRequest request, HttpServletResponse response) {
		String token = request.getParameter(Token.TOKEN);
		request.getSession().setAttribute(Token.TOKEN, token);
		System.out.println(token);
		UsernamePasswordToken t = new UsernamePasswordToken(token, SystemSession.PASSWORD);
		try {
			Subject s = SecurityUtils.getSubject();
			s.login(t);
			request.getSession().setAttribute("login", true);
			return "success";
		} catch (AuthenticationException e1) {
			e1.printStackTrace();
		}
		return "failure";
	}

	@RequestMapping("/sso/ro")
	@ResponseBody
	public boolean rlogout(HttpServletRequest request, HttpServletResponse response) {
		Subject s = SecurityUtils.getSubject();
		s.logout();
		request.getSession().removeAttribute("login");
		request.getSession().removeAttribute(Token.TOKEN);
		return true;
	}

}